/**
 * 荣誉Api
 * 设置学院的荣誉、战绩等数据
 */
const db = require('../../config/db')


/**
 * 更新球队的荣誉时刻
 */
exports.updateHonorMoment = async(req, res) => {
    try {
        const {csId, newHonorMoment} = req.body
        const sql = `UPDATE college_sport
                     SET honor_moment = ?
                     WHERE id = ?             
                     `
        const param = [newHonorMoment, csId]
        const [rows] = await db.query(sql, param)
        if(rows.affectedRows == 0)
            return res.status(201).json({error: "更新荣誉时刻失败!"})
        res.status(200).json({success: "更新荣誉时刻成功!"})
    } catch(err) {
        console.log("err:", err)
        res.status(500).json({error: "服务器错误，请稍后重试!"})
    }
}

/**
 * 更新球队介绍
 */
exports.updateIntroduction = async(req, res) => {
    try {
        const {csId, newIntroduction} = req.body
        const sql = `UPDATE college_sport
                     SET introduction = ?
                     WHERE id = ?             
                     `
        const param = [newIntroduction, csId]
        const [rows] = await db.query(sql, param)
        if(rows.affectedRows == 0)
            return res.status(201).json({error: "更新球队介绍失败!"})
        res.status(200).json({success: "更新球队介绍成功!"})
    } catch(err) {
        console.log("err:", err)
        res.status(500).json({error: "服务器错误，请稍后重试!"})
    }
}


/**
 * 获取x学院x运动队的战绩
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.getFight = async (req, res) => {
    try {
        const { college, sport } = req.body;
        const sql = `
            SELECT * FROM fight
            WHERE sport = ?
            AND (home_team = ? OR visit_team = ?)
            ORDER BY time DESC`
        const params = [sport, college, college];
        const [rows] = await db.query(sql, params);

        res.status(200).json(
            rows.map(row => {
                let resultText = "";
                switch (row.result) {
                    case 1:
                        if(row.home_team == college)
                            resultText = "胜";
                        else
                            resultText = "负"
                        break;
                    case 0:
                        resultText = "平";
                        break;
                    case 2:
                        if(row.visit_team == college) 
                            resultText = "胜";
                        else
                            resultText = "负";
                        break;
                    default:
                        resultText = "未知";
                }
                console.log("row.result: ", row.result)
                console.log("row.homeTeam: ", row.home_team)
                console.log("row.visitTeam: ", row.visit_team)
                console.log("resultText: ", resultText)

                return {
                    id: row.id,
                    sport: row.sport,
                    gameName: row.game_name,
                    gameType: row.game_type,
                    homeTeam: row.home_team,
                    visitTeam: row.visit_team,
                    fraction: row.fraction,
                    result: resultText,      // 原始数值
                    time: row.time
                };
            })
        );
    } catch (err) {
        console.log("err: ", err);
        res.status(500).json({ error: "服务器异常" });
    }
}


/**
 * 添加x学院x运动队的战绩
 * sport=足球时 需判断点球情况
 */
exports.addFight = async (req, res) => {
    try {
        const { sport, gameName, gameType, homeTeam, visitTeam, 
                homeScore, visitScore, homeScore2, visitScore2, time } = req.body;

        // todo 判断该战绩是否添加过，不能重复添加(暂时不考虑，后期需要再加上)
        
        let result;
        let fraction = homeScore + ":" + visitScore
        if (homeScore > visitScore) {
            result = 1; // 主胜
        } else if (homeScore < visitScore) {
            result = 2; // 客胜
        } else {
            // 判断是否经过点球
            // 有点球则分出胜负;否则则平局
            let isJudgePiont = homeScore2>=0 && visitScore2>=0
            console.log("isJudgePiont: ", isJudgePiont)
            if(isJudgePiont) {
                fraction += ('(' + homeScore2 + ':' + visitScore2 + ')')
                if(homeScore2 > visitScore2)
                    result = 1
                else
                    result = 2
            } else {
                result = 0; // 平局
            }
        }

        const sql = `
            INSERT INTO fight (sport, game_name, game_type, home_team, visit_team, fraction, result, time)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        `;
        const [rows] = await db.query(sql, [sport, gameName, gameType, homeTeam, visitTeam, fraction, result, time]);
        if(rows.affectedRows == 0) {
            return res.status(201).json({error: '战绩添加失败!'})
        }
        // todo 如果是决赛/季军赛，更新获得奖杯的队伍的奖杯数量
        let sql1
        let sql2
        let param1 = []
        let param2 = []
        let team1 = ""
        let team2 = ""
        if(gameType === "总决赛") {
            if(result == 1) {
                // 主队胜
                team1 = homeTeam
                team2 = visitTeam
            } else if(result == 2) {
                // 客队胜
                team1 = visitTeam
                team2 = homeTeam
            } else {
                return res.status(201).json({error: "决赛不可能平局!"})
            }

            // 更新冠军
            sql1 = `SELECT id, champion FROM college_sport
                        WHERE college = ? and sport = ?`
            param1.push(team1)
            param1.push(sport)
            const [rows1] = await db.query(sql1, param1)
            if(rows1.length == 0) {
                // 数据库还没有，新增一个
                sql2 = `INSERT INTO college_sport
                                (id, college, sport, champion, second_winner, third_winner, honor_moment, introduction)  
                                values
                                (?, ?, ?, ?, ?, ?, ?, ?)`
                param2 = [null, team1, sport, 1, 0, 0, "", ""]
                const [rows2] = await db.query(sql2, param2)
                if(rows2.affectedRows == 0){
                    return res.status(201).json({error: '战绩添加失败!'})
                }
            } else {
                // 数据库有，更新一个
                const row = rows1[0]
                const sql2 = `UPDATE college_sport
                              SET champion = ?
                              WHERE id = ?`
                param2 = [row.champion+1, row.id]
                const [rows2] = await db.query(sql2, param2)
                if(rows2.affectedRows == 0){
                    return res.status(201).json({error: '战绩添加失败!'})
                }
            }

            // 更新亚军
            sql1 = `SELECT id, second_winner FROM college_sport
                        WHERE college = ? and sport = ?`
            param1 = []
            param1.push(team2)
            param1.push(sport)
            const [rows3] = await db.query(sql1, param1)
            if(rows3.length == 0) {
                // 数据库还没有，新增一个
                sql2 = `INSERT INTO college_sport
                                (id, college, sport, champion, second_winner, third_winner, honor_moment, introduction)  
                                values
                                (?, ?, ?, ?, ?, ?, ?, ?)`
                param2 = [null, team2, sport, 0, 1, 0, "", ""]
                const [rows4] = await db.query(sql2, param2)
                if(rows4.affectedRows == 0){
                    return res.status(201).json({error: '战绩添加失败!'})
                }
            } else {
                // 数据库有，更新一个
                const row = rows3[0]
                const sql2 = `UPDATE college_sport
                              SET second_winner = ?
                              WHERE id = ?`
                param2 = [row.second_winner+1, row.id]
                const [rows4] = await db.query(sql2, param2)
                if(rows4.affectedRows == 0){
                    return res.status(201).json({error: '战绩添加失败!'})
                }
            }
        } else if(gameType === "季军赛") {
            if(result == 1) {
                // 主队胜
                team1 = homeTeam
            } else if(result == 2) {
                // 客队胜
                team1 = visitTeam
            } else {
                return res.status(201).json({error: "季军赛不可能平局!"})
            }
            
            // 更新季军信息
            sql1 = `SELECT id, third_winner FROM college_sport
                        WHERE college = ? and sport = ?`
            param1 = []
            param1.push(team1)
            param1.push(sport)
            const [rows1] = await db.query(sql1, param1)
            if(rows1.length == 0) {
                // 数据库还没有，新增一个
                sql2 = `INSERT INTO college_sport
                                (id, college, sport, champion, second_winner, third_winner, honor_moment, introduction)  
                                values
                                (?, ?, ?, ?, ?, ?, ?, ?)`
                param2 = [null, team1, sport, 0, 0, 1, "", ""]
                const [rows2] = await db.query(sql2, param2)
                if(rows2.affectedRows == 0){
                    return res.status(201).json({error: '战绩添加失败!'})
                }
            } else {
                // 数据库有，更新一个
                const row = rows1[0]
                const sql2 = `UPDATE college_sport
                              SET third_winner = ?
                              WHERE id = ?`
                param2 = [row.third_winner+1, row.id]
                const [rows2] = await db.query(sql2, param2)
                if(rows2.affectedRows == 0){
                    return res.status(201).json({error: '战绩添加失败!'})
                }
            }
        }
        res.status(200).json({ id: rows.insertId, message: '战绩添加成功!' });
    } catch (err) {
        console.error('addFight error:', err);
        return res.status(500).json({ error: "服务器异常，请稍后重试！" });
    }
}

/**
 * 更新x学院x运动队的战绩
 */
exports.updateFight = async (req, res) => {
    try {
        const { id, gameName, gameType, college, sport, homeTeam, visitTeam, fraction, time } = req.body;

        // 检查必填字段
        if (!id) {
            return res.status(400).json({ error: '缺少比赛 ID' });
        }

        if (!fraction || !fraction.includes(':')) {
            return res.status(400).json({ error: '比分格式错误，应为 x:y' });
        }

        const [homeScore, visitScore] = fraction.split(':').map(Number);

        let result;
        if (homeScore > visitScore) {
            result = 1; // 主胜
        } else if (homeScore < visitScore) {
            result = 2; // 客胜
        } else {
            result = 0; // 平局
        }

        const sql = `
            UPDATE fight
            SET game_name = ?, game_type = ?, college = ?, sport = ?, home_team = ?, visit_team = ?, fraction = ?, result = ?, time = ?
            WHERE id = ?
        `;

        const [rows] = await db.query(sql, [gameName, gameType, college, sport, homeTeam, visitTeam, fraction, result, time, id]);

        if (rows.affectedRows === 0) {
            return res.status(404).json({ error: '未找到要更新的比赛记录' });
        }

        res.status(200).json({ message: '比赛记录更新成功' });

    } catch (err) {
        console.error('updateFight error:', err);
        return res.status(500).json({ error: "服务器异常，请稍后重试！" });
    }
}

/**
 * Delete fight data
 * update the data of fight and college_sport 
 */
exports.deleteFight = async(req, res) => {
    try {
        const {fightId} = req.body
        const sql = `SELECT sport, game_type, home_team, visit_team, result FROM fight
                     where id = ?`
        const [rows] = await db.query(sql, [fightId])
        if(rows.length == 0) {
            return res.status(201).json({error: 'Not find the fight id!'})
        }
        const row = rows[0]
        const gameType = row.game_type
        const homeTeam = row.home_team
        const visitTeam = row.visit_team
        const sport = row.sport
        const result = row.result
        let sql1
        let param1 = []
        let param2 = []
        let team1 = ""
        let team2 = ""
        if(gameType === "总决赛") {
            if(result > 0) {
                if(result == 1) {
                    // 主队胜
                    team1 = homeTeam
                    team2 = visitTeam
                } else if(result == 2) {
                    // 客队胜
                    team1 = visitTeam
                    team2 = homeTeam
                }

                // 更新冠军
                sql1 = `SELECT id, champion FROM college_sport
                            WHERE college = ? and sport = ?`
                param1.push(team1)
                param1.push(sport)
                const [rows1] = await db.query(sql1, param1)
                
                // 数据库必有，更新-1
                if(rows1.length != 0) {
                    const row = rows1[0]
                    const sql2 = `UPDATE college_sport
                                SET champion = ?
                                WHERE id = ?`
                    param2 = [row.champion-1, row.id]
                    const [rows2] = await db.query(sql2, param2)
                    if(rows2.affectedRows == 0){
                        return res.status(201).json({error: '战绩添加失败!'})
                    }
                } else {
                    return res.status(201).json({error: "删除失败!数据有误!\n找不到冠军信息!"})
                }
                

                // 更新亚军
                sql1 = `SELECT id, second_winner FROM college_sport
                            WHERE college = ? and sport = ?`
                param1 = []
                param1.push(team2)
                param1.push(sport)
                const [rows3] = await db.query(sql1, param1)
                if(rows3.length != 0) {
                    // 数据库有，更新一个
                    const row = rows3[0]
                    const sql2 = `UPDATE college_sport
                                SET second_winner = ?
                                WHERE id = ?`
                    param2 = [row.second_winner-1, row.id]
                    const [rows4] = await db.query(sql2, param2)
                    if(rows4.affectedRows == 0){
                        return res.status(201).json({error: '战绩添加失败!'})
                    }
                } else {
                    return res.status(201).json({error: "删除失败!数据有误!\n找不到亚军信息!"})
                }
            }
            
        } else if(gameType === "季军赛") {
            if(result > 0) {
                if(result == 1) {
                    // 主队胜
                    team1 = homeTeam
                } else if(result == 2) {
                    // 客队胜
                    team1 = visitTeam
                }
                
                // 更新季军信息
                sql1 = `SELECT id, third_winner FROM college_sport
                            WHERE college = ? and sport = ?`
                param1 = []
                param1.push(team1)
                param1.push(sport)
                const [rows1] = await db.query(sql1, param1)
                if(rows1.length != 0) {
                    // 数据库有，更新一个
                    const row = rows1[0]
                    const sql2 = `UPDATE college_sport
                                SET third_winner = ?
                                WHERE id = ?`
                    param2 = [row.third_winner-1, row.id]
                    const [rows2] = await db.query(sql2, param2)
                    if(rows2.affectedRows == 0){
                        return res.status(201).json({error: '战绩添加失败!'})
                    }
                } else {
                    return res.status(201).json({error: "删除失败!数据有误!\n找不到季军信息!"})
                }
            }
            
        }
        const sql3 = `DELETE FROM fight
                      WHERE id = ?`
        const [rows3] = await db.query(sql3, [fightId])
        if(rows3.affectedRows == 0) {
            return res.status(201).json({error: "删除战绩失败!"})
        }
        res.status(200).json({msg: "删除战绩成功!"})
    } catch(err) {
        console.error('deleteHonor error:', err)
        return res.status(500).json({error: '服务器异常，请稍后重试!'})
    }
}

